package slxy.jiangtao.dts.service.sys;

import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.pdf.BaseFont;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import slxy.jiangtao.dts.core.common.bean.Constants;
import slxy.jiangtao.dts.core.common.service.CommonService;
import slxy.jiangtao.dts.core.util.DateUtils;
import slxy.jiangtao.dts.core.util.StringUtil;
import slxy.jiangtao.dts.core.util.UUIDGenerator;
import slxy.jiangtao.dts.core.util.WordUtils;
import slxy.jiangtao.dts.entity.sys.News;
import slxy.jiangtao.dts.entity.sys.SystemFiles;
import slxy.jiangtao.dts.entity.sys.User;

import java.io.File;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Code must be sexy
 * Created by Jiang Tao on 2017/4/30.
 * 说明：
 */
@Service("newsService")
public class NewsService {
    @Autowired
    CommonService commonService;
    @Autowired
    SystemFileService systemFileService;

    /**
     * 添加新闻
     */
    public Integer addOrUpdate(News record, User user) throws Exception {
        if(StringUtil.isEmpty(record.getCreator())){
            record.setCreator(user.getName());
        }
        if(StringUtil.isEmpty(record.getUploadTime())){
            record.setUploadTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
        }
        commonService.saveOrUpdate(record);
        saveWord(record);
        return record.getId();
    }

    /**
     * 删除一个新闻
     */
    public void delete(Integer newsId) {
        News news = commonService.get(News.class, newsId);
        systemFileService.deleteFileByNo(news.getFileNo());
        commonService.delete(news);
    }

    /**
     * 新闻内容保存为word文件提供下载
     */
    public void saveWord(News news) throws Exception {
        if(StringUtil.isEmpty(news.getContent())){
            return;
        }
        WordUtils wordUtils = new WordUtils();
        String fileno = "";
        if (news.getFileNo() == null) {//说明是第一次执行此操作
            fileno = UUIDGenerator.generate();
        } else {
            fileno = news.getFileNo();
        }
        String savename = fileno +"."+ Constants.WORD_fileExt;//保存时的文件名
        String localPath = Constants.UEDITOR_PATH + File.separator + "news" + File.separator + DateUtils.getDate("yyyy/MM");
        File file = new File(localPath);
        //判断文件夹是否存在,如果不存在则创建文件夹
        if (!file.exists()) {
            file.mkdirs();
        }
        wordUtils.openDocument(localPath + File.separator + savename);
        wordUtils.insertTitle(news.getTitle(),14, Font.BOLD, Element.ALIGN_CENTER);
        StyleSheet ss = new StyleSheet();
        Paragraph context = new Paragraph();
        context.setAlignment(Element.ALIGN_LEFT);
        //设置行距
        context.setLeading(3f);
        // 离上一段落（标题）空的行数
        context.setSpacingBefore(1);
        // 设置第一行空的列数
        context.setFirstLineIndent(20);
        String neirong = Constants.WORD_REPORTOR_ONE+news.getReporterText()+Constants.WORD_REPORTOR_TWO
                +news.getReporterPhoto()+Constants.WORD_REPORTOR_THREE
                +news.getReleaseTime()+Constants.WORD_REPORTOR_FOUR
                +news.getContent();
        List htmlList = HTMLWorker.parseToList(new StringReader(neirong), ss);
        for (int i = 0; i < htmlList.size(); i++) {
            com.lowagie.text.Element e = (com.lowagie.text.Element) htmlList
                    .get(i);
            context.add(e);
        }
        wordUtils.getDocument().add(context);
        wordUtils.closeDocument();

        //待doc保存成功后再保存文件
        if (news.getFileNo() == null) {//说明是第一次执行此操作
            news.setFileNo(fileno);
            commonService.updateEntity(news);

            SystemFiles systemFiles = new SystemFiles();
            systemFiles.setNo(fileno);
            systemFiles.setName(news.getTitle());
            systemFiles.setLocalPath(localPath);
            systemFiles.setType("news");
            systemFiles.setOperTime(news.getUploadTime());
            systemFiles.setOperName(news.getCreator());
            systemFiles.setSuffix(Constants.WORD_fileExt);
            commonService.save(systemFiles);
        } else {//存在修改文件名的可能
            SystemFiles systemFiles = commonService.get(SystemFiles.class, news.getFileNo());
            systemFiles.setName(news.getTitle());
            System.out.println("sdf");
            commonService.updateEntity(systemFiles);
        }
    }
}
